#! -*- coding:utf-8 -*-
import logging
from datetime import datetime, timedelta

from django.core.management.base import BaseCommand

from common.cache.redis_cache import del_bank_card_special_amount
from common.order.model import Order, PAY_STATUS, NOTIFY_STATUS
from common.mch import handler as mch_handler

_LOGGER = logging.getLogger('worker')


# cd /home/ubuntu/af-env/hydra;/home/ubuntu/af-env/bin/python manage.py

class Command(BaseCommand):

    def handle(self, **options):
        print 'start'
        _LOGGER.info('expire_order start')
        start = datetime.utcnow() + timedelta(minutes=-20)
        items = Order.query.filter(Order.created_at < start).filter(
            Order.status == PAY_STATUS.READY).all()
        print 'total : %s' % len(items)
        count = 0
        for item in items:
            item.status = PAY_STATUS.OVERTIME
            item.save()
            print count
            count = count + 1
            del_bank_card_special_amount(item.bankcard_num, item.real_amount)
        print 'end'
        _LOGGER.info('expire_order end')
